package com.googlecode.vanaraha.data
import com.googlecode.vanaraha.utils.Utils._

class DuplicateElement(val startLineNo: Int, val endLineNo: Int, 
                       issueSource: SourceFile) extends SingleFileIssue(issueSource) with Ordered[DuplicateElement]{
  var duplicateSet: DuplicateSet = _
  
  override def compare(other: DuplicateElement) =
    if(other != this){
	    val srcCompare = this.issueSource.compareTo(other.issueSource)
	    if(srcCompare==0) this.startLineNo - other.startLineNo else srcCompare
    }else 0
   
   override def equals(obj: Any) = obj match{
     case other: DuplicateElement =>
       issueSource == other.issueSource && startLineNo == other.startLineNo && endLineNo == other.endLineNo
     case _ => false
   }
   override def toString = %%("[ duplicateElement ] src: %s | start: %d | end: %d",issueSource, startLineNo, endLineNo) 
   override def hashCode = issueSource.hashCode * 3 + startLineNo * endLineNo
}

class DuplicateSet(val lineCount:Int, val duplicateElements: Array[DuplicateElement], val duplicatedTxt: String)
       extends MultipleFileIssue(duplicateElements.map(_.issueSource).unique){
   scala.util.Sorting.stableSort(duplicateElements) // sort the duplicate elements based on line numbers.
   duplicateElements.foreach( _.duplicateSet = this)
   
   def this(lineCount: Int, dupEl: Array[DuplicateElement]) = this(lineCount, dupEl, "")
   
   def sourceTypeOfFiles = if(issueSources.length > 0) issueSources(0).srcType else SourceType.NOT_A_SOURCE
  
   override def equals(obj: Any) = obj match{
     case other: DuplicateSet => 
       this == other || lineCount == other.lineCount && duplicateElements.deepEquals(other.duplicateElements)
     case _ => false
   }
   
   override def hashCode = lineCount * ( 3 /: duplicateElements.map(_.hashCode)) (_ + _) * duplicatedTxt.hashCode
   
   override def toString = %%("[ DuplicateSet ] lineCount : %d\n--Duplicate Elements--\n%s",
                                     lineCount, duplicateElements.mkString("\n{"," \n| ", "}\n"))
}